package hooks

import (
	"encoding/json"
	"fmt"
	"github.com/sirupsen/logrus"
	"gopkg.in/gomail.v2"
	"strings"
)

const (
	format = "20060102 15:04:05"
)


// MailAuthHook to sends logs by email with authentication.
type MailAuthHook struct {
	AppName  string
	Host     string
	Port     int
	From     string
	To       []string
	Username string
	Password string

	levels []logrus.Level
}

// NewMailAuthHook creates a hook to be added to an instance of logger.

func NewMailAuthHook(appname string, host string, port int, from string, to []string, username string, password string, levels []logrus.Level) (*MailAuthHook, error) {

	return &MailAuthHook{
		AppName:  appname,
		Host:     host,
		Port:     port,
		From:     from,
		To:       to,
		Username: username,
		Password: password,
		levels: levels,
	}, nil
}

// Fire is called when a log event is fired.
func (hook *MailAuthHook) Fire(entry *logrus.Entry) error {

	loggerLevel :=entry.Level.String()

	if loggerLevel == "error"{

		if strings.Contains(entry.Message,"Error reading next available message"){

			return nil
		}
	}

	body := entry.Time.Format(format) + " - " + entry.Message
	fields, _ := json.MarshalIndent(entry.Data, "", "\t")
	contents := fmt.Sprintf(" \n\n%s\r\n\r\n%s", body, fields)

	m:= gomail.NewMessage()
	m.SetHeader("From",hook.From)
	m.SetHeader("To",hook.To...)
	m.SetAddressHeader("Cc","jion_cc@163.com","Abner")
	m.SetHeader("Subject", hook.AppName+"-"+entry.Level.String())
	m.SetBody("text/plain;charset=utf-8", contents)

	// try send email
	d := gomail.NewDialer(hook.Host, hook.Port, hook.Username, hook.Password)

	// Send the email to Bob, Cora and Dan.
	if err := d.DialAndSend(m); err != nil {
		fmt.Println("邮件服务错误：",err)
		//logger.Log.Error("send Email error:",err)
	}

	return nil
}

// Levels returns the available logging levels.
func (hook *MailAuthHook) Levels() []logrus.Level {
	return hook.levels
}
